package logic

import (
	"context"
	"fmt"
	"strconv"
	"user3/model/mysql"
	"user3/model/redis"
	"user3/pkg"

	"user3/userrpc/internal/svc"
	"user3/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateLogic {
	return &UpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateLogic) Update(in *userrpc.UpdateRequest) (*userrpc.UpdateResponse, error) {
	// todo: add your logic here and delete this line
	get := redis.Client.Get("captchaupdate" + in.Account)
	if get.Val() != in.Code {
		return nil, fmt.Errorf("图形验证码错误,请重新尝试")
	}
	cmd := redis.Client.Get("sendsmsupdate" + in.Account)
	if cmd.Val() != in.Send {
		return nil, fmt.Errorf("短信验证码错误，请重新尝试")
	}
	var user mysql.User
	if user.Password == pkg.Md5(in.Newpass) {
		return nil, fmt.Errorf("原密码不能和新密码一致")
	}

	if in.Newpass != in.Password {
		return nil, fmt.Errorf("两次输入密码不一样")
	}
	user.Password = pkg.Md5(in.Newpass)

	redis.Client.Del("captchaupdate" + in.Account)

	redis.Client.Del("sendsmsupdate" + in.Account)

	return &userrpc.UpdateResponse{Id: strconv.Itoa(int(user.ID))}, nil
}
